package com.raos.validation.service;

import com.raos.validation.annotation.ListNotHaveNull;
import org.springframework.stereotype.Service;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;

/**
 * 自定义注解 ListNotHaveNull 的实现类
 * 用于判断 List 集合中是否含有 null 元素
 *
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2021/5/20 09:26
 */
@Service
public class ListNotHaveNullValidatorImpl implements ConstraintValidator<ListNotHaveNull, List> {

    private int value;

    @Override
    public void initialize(ListNotHaveNull constraintAnnotation) {
        //传入value 值，可以在校验中使用
        this.value = constraintAnnotation.value();
    }

    public boolean isValid(List list, ConstraintValidatorContext constraintValidatorContext) {
        for (Object object : list) {
            if (object == null) {
                //如果List集合中含有Null元素，校验失败
                return false;
            } else if (object instanceof String) {
                String value = object.toString();
                if (value.trim().length() == 0){
                    return false;
                }
            }
        }
        return true;
    }

}
